const AV = require("leanengine");
const BaseService = require("./baseService");
const Mock = require("mockjs");

class Service extends BaseService {
  constructor() {
    let attrs = ["phone", "smsCode"];
    super("Student", attrs);
  }

  // 登陆
  async loginBySmsCode(ctx) {
    const {
      phone,
      smsCode
    } = ctx.params;
    if (!phone || !smsCode) {
      return {
        code: "600",
        msg: "请输入手机号码或验证码",
      };
    }

    try {
      const query = new AV.Query("Student");
      query.equalTo("phone", String(phone));
      query.equalTo("smsCode", Number(smsCode));
      let result = await query.find();
      if (result.length > 0) {
        let obj = result[0];
        return {
          code: "666",
          msg: "登录成功",
          userId: obj.id,
          ...obj._serverData
        };
      } else {
        return {
          code: "602",
          msg: "验证码错误",
        };
      }
    } catch (err) {
      return {
        code: err.code,
        msg: err.message,
      };
    }
  }

  // // 获取验证码
  async getSmsCode(ctx) {
    let {
      phone
    } = ctx.params;
    if (!phone) {
      return {
        code: "602",
        msg: "请输入电话号码",
      };
    }
    let smsCode = Mock.Random.integer(1000, 9999);

    try {
      const query = new AV.Query("Student");
      query.equalTo("phone", String(phone));
      let result = await query.find();
      if (result.length > 0) {
        const entry = AV.Object.createWithoutData("Student", result[0].id);
        entry.set("smsCode", smsCode);
        entry.save();
      } else {
        this.addInterface({
          phone: String(phone),
          smsCode: Number(smsCode),
        });
      }

      setTimeout(async () => {
        let result = await query.find();
        const entry = AV.Object.createWithoutData("Student", result[0].id);
        entry.set("smsCode", 1234);
        entry.save();
      }, 120000);

      return {
        code: 666,
        msg: "验证码已发送,有效时间为2分钟",
        smsCode,
      };
    } catch (err) {
      return {
        code: err.code,
        msg: err.message,
      };
    }
  }

  async logout(ctx) {
    try {
      AV.User.logOut();
      return {
        code: "666",
        msg: "登出成功",
      };
    } catch (error) {
      return {
        code: "602",
        msg: "登出失败",
        ...error,
      };
    }
  }
}

module.exports = new Service();